package com.easylinkin.linkappapi.inspection.service.impl;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.service.OSSService;
import com.easylinkin.linkappapi.common.utils.file.FileExt;
import com.easylinkin.linkappapi.common.utils.file.ZipFileUtil;
import com.easylinkin.linkappapi.facerecognition.service.oss.ObjectStorageInternalService;
import com.easylinkin.linkappapi.inspection.dto.AppElectricBoxDTO;
import com.easylinkin.linkappapi.inspection.dto.ElectricBoxDTO;
import com.easylinkin.linkappapi.inspection.dto.ElectricCheckDTO;
import com.easylinkin.linkappapi.inspection.dto.ElectricCheckPhotoAlbumDTO;
import com.easylinkin.linkappapi.inspection.dto.ElectricCheckPhotoAlbumQueryDTO;
import com.easylinkin.linkappapi.inspection.dto.ElectricOptionDTO;
import com.easylinkin.linkappapi.inspection.entity.ElectricBox;
import com.easylinkin.linkappapi.inspection.entity.ElectricCheck;
import com.easylinkin.linkappapi.inspection.entity.ElectricOption;
import com.easylinkin.linkappapi.inspection.entity.ElectricStatistics;
import com.easylinkin.linkappapi.inspection.mapper.ElectricBoxMapper;
import com.easylinkin.linkappapi.inspection.mapper.ElectricCheckMapper;
import com.easylinkin.linkappapi.inspection.mapper.ElectricStatisticsMapper;
import com.easylinkin.linkappapi.inspection.service.ElectricCheckService;
import com.easylinkin.linkappapi.inspection.service.ElectricOptionService;
import com.easylinkin.linkappapi.inspection.service.ElectricStatisticsService;
import com.easylinkin.linkappapi.photoalbum.util.ExportUtil;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.security.mapper.LinkappUserMapper;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.mapper.LinkappTenantMapper;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * <p>
 * 配电箱巡检表 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2022-04-13
 */
@Slf4j
@Service
public class ElectricCheckServiceImpl extends
    ServiceImpl<ElectricCheckMapper, ElectricCheck> implements ElectricCheckService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  @Autowired
  private ElectricStatisticsService electricStatisticsService;

  @Autowired
  private ElectricBoxMapper electricBoxMapper;

  @Autowired
  private ElectricCheckMapper electricCheckMapper;

  @Autowired
  private ElectricOptionService electricOptionService;

  @Autowired
  private ElectricStatisticsMapper electricStatisticsMapper;

  @Autowired
  private LinkappUserMapper linkappUserMapper;

  @Autowired
  private OSSService ossService;

  @Autowired
  private LinkappTenantMapper linkappTenantMapper;

  /**
   * 增加
   *
   * @param electricCheck
   * @return 是新增返回true 修改返回false
   */
  @Override
  public Boolean insert(ElectricCheck electricCheck) {
    //是否为新增
    Boolean isInsert = false;
    /**
     * 验证重复
     */
//    this.checkExist(electricCheck);
    if (StringUtils.isBlank(electricCheck.getId())){
      Date checkTime = electricCheck.getCheckTime();
      //判断时间是否为空，为空查询最近的
      ElectricCheck todayCheck = null;
      QueryWrapper<ElectricCheck> queryWrapper = new QueryWrapper<>();
      if (null != checkTime){
        queryWrapper.eq("electric_box_id_",electricCheck.getElectricBoxId());
        queryWrapper.ge("check_time_", DateUtil.beginOfDay(checkTime))
            .le("check_time_",DateUtil.endOfDay(checkTime)).orderByDesc("check_time_");
        List<ElectricCheck> electricChecks = electricCheckMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(electricChecks)) {
          todayCheck = electricChecks.get(0);
        }
      }
      if(null == todayCheck){
        //设置基本属性
        this.setBase(electricCheck);
        this.save(electricCheck);
        isInsert = true;
      }else{
        electricCheck.setId(todayCheck.getId());
        //设置基本属性
        this.setBase(electricCheck);
        this.updateById(electricCheck);
      }
    }else {
      //设置基本属性
      this.setBase(electricCheck);
      this.updateById(electricCheck);
    }
    return isInsert;
  }

  /**
   * 根据id编辑
   * @param electricCheck
   */
  @Override
  public void updateOne(ElectricCheck electricCheck) {
    /**
     * 验证重复
     */
//    this.checkExist(electricCheck);
    //设置基本属性
    this.setBase(electricCheck);
    this.updateById(electricCheck);
  }

  /**
   * @Description: 根据配电箱id和日期查询巡检项情况
   *               时间格式 2022-05-01
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public AppElectricBoxDTO findByIdAndDate(ElectricBoxDTO electricBoxDTO) {
    //查询配电箱基本信息
    ElectricBox electricBox = electricBoxMapper.findById(electricBoxDTO.getId());
    //验证是否属于同一个项目
    if (null != linkappUserContextProducer.getCurrent()){
      if (!electricBox.getTenantId().equals(linkappUserContextProducer.getCurrent().getTenantId())){
        throw new BusinessException("该配电箱不属于该工地");
      }
    }
    AppElectricBoxDTO appElectricBoxDTO = new AppElectricBoxDTO();
    appElectricBoxDTO.setElectricBoxDTO(BeanUtil.copyProperties(electricBox,ElectricBoxDTO.class));
    //查询巡检信息
    ElectricCheckDTO electricCheckDTO = new ElectricCheckDTO();
    Date checkTime = electricBoxDTO.getCheckTime();
    //判断时间是否为空，为空查询最近的
    ElectricCheck electricCheck = null;
    QueryWrapper<ElectricCheck> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("electric_box_id_",electricBoxDTO.getId());
    if (null != checkTime){
      queryWrapper.ge("check_time_", DateUtil.beginOfDay(checkTime))
          .le("check_time_",DateUtil.endOfDay(checkTime)).orderByDesc("check_time_");
      List<ElectricCheck> electricChecks = electricCheckMapper.selectList(queryWrapper);
      if(CollectionUtil.isNotEmpty(electricChecks)) {
        electricCheck = electricChecks.get(0);
      }
    }else {
      //查询最近的
      queryWrapper.orderByDesc("check_time_");
      List<ElectricCheck> electricChecks = electricCheckMapper.selectList(queryWrapper);
      if (null != electricChecks && electricChecks.size() > 0){
        electricCheck = electricChecks.get(0);
      }
    }

    if (null != electricCheck){
      electricCheckDTO = BeanUtil.copyProperties(electricCheck,ElectricCheckDTO.class);
      LinkappUser linkappUser = linkappUserMapper.selectById(electricCheckDTO.getCheckUserId());
      if (null != linkappUser){
        electricCheckDTO.setCheckUserName(linkappUser.getNickname());
      }
      //处理检查项
      String content = electricCheck.getContent();
      List<ElectricOptionDTO> optionList = JSONUtil.toList(content, ElectricOptionDTO.class);
      electricCheckDTO.setElectricOptionList(optionList);
    }else {
      //查询检查项
      List<ElectricOption> options = electricOptionService.optionsByTenantId(electricBox.getTenantId());
      List<ElectricOptionDTO> optionDTOS = BeanUtil
          .copyToList(options, ElectricOptionDTO.class);
      electricCheckDTO.setElectricOptionList(optionDTOS);
    }
    appElectricBoxDTO.setElectricCheckDTO(electricCheckDTO);
    return appElectricBoxDTO;
  }

  @Override
  public ElectricCheckDTO findCheckStatusByIdAndDate(ElectricBoxDTO electricBoxDTO) {
    //查询巡检信息
    ElectricCheckDTO electricCheckDTO = null;
    Date checkTime = electricBoxDTO.getCheckTime();
    //判断时间是否为空，为空查询最近的
    ElectricCheck electricCheck = null;
    QueryWrapper<ElectricCheck> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("electric_box_id_",electricBoxDTO.getId());
    if (null == checkTime){
     return null;
    }
    queryWrapper.ge("check_time_", DateUtil.beginOfDay(checkTime))
        .le("check_time_",DateUtil.endOfDay(checkTime)).orderByDesc("check_time_");
    List<ElectricCheck> electricChecks = electricCheckMapper.selectList(queryWrapper);
    if(CollectionUtil.isNotEmpty(electricChecks)){
      electricCheck = electricChecks.get(0);
      if (null != electricCheck){
        electricCheckDTO = BeanUtil.copyProperties(electricCheck,ElectricCheckDTO.class);
        LinkappUser linkappUser = linkappUserMapper.selectById(electricCheckDTO.getCheckUserId());
        if (null != linkappUser){
          electricCheckDTO.setCheckUserName(linkappUser.getNickname());
        }
        String content = electricCheck.getContent();
        List<ElectricOptionDTO> optionList = JSONUtil.toList(content, ElectricOptionDTO.class);
        electricCheckDTO.setElectricOptionList(optionList);
        List<ElectricOptionDTO> optionDTOS = optionList.stream()
            .filter(o -> Integer.valueOf(0).equals(o.getValue())).collect(Collectors.toList());
        electricCheckDTO.setResult(optionDTOS.size()<1);
        return electricCheckDTO;
      }
    }
    return null;
  }

  /**
   * @Description: 巡检提交
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public void check(ElectricCheckDTO electricCheckDTO) {
    //将巡检项转换为json
    List<ElectricOptionDTO> optionList = electricCheckDTO.getElectricOptionList();
    String s = JSONUtil.toJsonStr(optionList);
    electricCheckDTO.setContent(s);
    ElectricCheck electricCheck = BeanUtil.copyProperties(electricCheckDTO, ElectricCheck.class);
    electricCheck.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    electricCheck.setCheckTime(new Date());
    electricCheck.setCheckUserId(linkappUserContextProducer.getCurrent().getId());
    //处理照片
    List<String> photoList = electricCheckDTO.getPhotoList();
    if (null != photoList && photoList.size() > 0){
      List<String> newList = new ArrayList<>();
      photoList.forEach(p ->{
        if (p.startsWith("http")){
          newList.add(p);
        }else{
          newList.add(ossService.saveImgBase64(p,"electricCheck.png"));
        }
      });
      electricCheck.setPhoto(StringUtils.join(newList,","));
    }
    //判断是否已经巡检
    Boolean isInsert = this.insert(electricCheck);
    //是否要修改
//    Boolean editFlag = StringUtils.isNotBlank(electricCheck.getId())?true:false;
    //修改当天巡检统计，数量加一
    if (isInsert){
      toCount(electricCheck.getCheckTime());
    }
  }

  /**
   * 统计巡检
   */
  private void toCount(Date checkTime) {
    QueryWrapper<ElectricStatistics> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("record_time_", DateUtil.beginOfDay(checkTime))
        .eq("tenant_id_",linkappUserContextProducer.getNotNullCurrent().getTenantId());
    List<ElectricStatistics> statistics = electricStatisticsMapper.selectList(queryWrapper);
    if (null != statistics && statistics.size() > 0){
      ElectricStatistics electricStatistics = statistics.get(0);
      electricStatistics.setDone(null==electricStatistics.getDone()?1:electricStatistics.getDone()+1);
      electricStatisticsMapper.updateById(electricStatistics);
    }else {
      //新增
      electricStatisticsService.countToday(linkappUserContextProducer.getNotNullCurrent().getTenantId(),1);
    }
  }

  @Override
  public IPage<ElectricCheckDTO> queryListByPage(RequestModel<ElectricCheckDTO> requestModel) {
    Page page = requestModel.getPage();
    ElectricCheckDTO electricCheck = requestModel.getCustomQueryParams();
    //项目id 过滤
    electricCheck.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    if(Objects.equals(electricCheck.getQueryType(),3)){
      electricCheck.setStatus(1);
    }
    IPage<ElectricCheckDTO> electricCheckIPage = baseMapper.queryListByPage(page, electricCheck);
    electricCheckIPage.getRecords().forEach(e ->{
      //处理检查项
      String content = e.getContent();
      List<ElectricOptionDTO> optionList = JSONUtil.toList(content, ElectricOptionDTO.class);
      List<ElectricOptionDTO> optionDTOS = optionList.stream()
          .filter(o -> Integer.valueOf(0).equals(o.getValue())).collect(Collectors.toList());
      e.setResult(optionDTOS.size()<1);
    });
    //0全部，1已巡检，2未巡检，3异常
    if(Objects.equals(electricCheck.getQueryType(),0)){
      //如果是全部，则一定要给这条统计的stasticId
      Assert.notNull(electricCheck.getStasticId(),"全部查询条件下，stasticId不能为空");
      ElectricStatistics electricStatistics = electricStatisticsMapper
          .selectById(electricCheck.getStasticId());
      String sumId = electricStatistics.getSumId();
      if(StringUtils.isNotBlank(sumId)){
        List<String> existIds = electricCheckIPage.getRecords().stream()
            .map(item -> item.getElectricBoxId()).collect(Collectors.toList());
        List<String> boxIds = Arrays.asList(sumId.split(","));
//        b.nickname checkUserName,
//        b.phone,
//            box.type_,
//            box.code_,
//            box.position_ electricBoxPosition
        boxIds.forEach(item->{
          if(!existIds.contains(item)){
            ElectricCheckDTO electricCheckDTO = new ElectricCheckDTO();
            ElectricBox box = electricBoxMapper.findById(item);
            electricCheckDTO.setElectricBoxId(item);
            if(box!=null){
              electricCheckDTO.setCheckUserName(box.getLeadName());
              electricCheckDTO.setPhone(box.getTelephone());
              electricCheckDTO.setType(box.getType());
              electricCheckDTO.setCode(box.getCode());
              electricCheckDTO.setElectricBoxPosition(box.getPosition());
              electricCheckDTO.setResult(null);
            }
            electricCheckIPage.getRecords().add(electricCheckDTO);
          }
        });
      }
    }
    //2未巡检
    if(Objects.equals(electricCheck.getQueryType(),2)){
      //如果是未巡检，则一定要给这条统计的stasticId
      Assert.notNull(electricCheck.getStasticId(),"未巡检条件下，stasticId不能为空");
      ElectricStatistics electricStatistics = electricStatisticsMapper
          .selectById(electricCheck.getStasticId());
      String sumId = electricStatistics.getSumId();
      List<ElectricCheckDTO> electricCheckDTOS = new ArrayList<>();
      if(StringUtils.isNotBlank(sumId)){
        List<String> existIds = electricCheckIPage.getRecords().stream()
            .map(item -> item.getElectricBoxId()).collect(Collectors.toList());
        List<String> boxIds = Arrays.asList(sumId.split(","));
        boxIds.forEach(item->{
          if(!existIds.contains(item)){
            ElectricCheckDTO electricCheckDTO = new ElectricCheckDTO();
            ElectricBox box = electricBoxMapper.findById(item);
            electricCheckDTO.setElectricBoxId(item);
            if(box!=null){
              electricCheckDTO.setCheckUserName(box.getLeadName());
              electricCheckDTO.setPhone(box.getTelephone());
              electricCheckDTO.setType(box.getType());
              electricCheckDTO.setCode(box.getCode());
              electricCheckDTO.setElectricBoxPosition(box.getPosition());
              electricCheckDTO.setResult(null);
            }
            electricCheckDTOS.add(electricCheckDTO);
          }
        });
      }
      IPage<ElectricCheckDTO> iPage = new Page<ElectricCheckDTO>();
      iPage.setRecords(electricCheckDTOS);
      return iPage;
    }
    return electricCheckIPage;
  }

  /**
   * 验证重复
   */
  private void checkExist(ElectricCheck electricCheck) {
    QueryWrapper<ElectricCheck> queryWrapper = new QueryWrapper<>();
    //设置判断重复条件
    queryWrapper.ge("check_time_", DateUtil.beginOfDay(electricCheck.getCheckTime()))
        .le("check_time_",DateUtil.endOfDay(electricCheck.getCheckTime()))
        .eq("electric_box_id_",electricCheck.getElectricBoxId());
    //编辑的时候存在id
    Optional.ofNullable(electricCheck.getId()).ifPresent(id -> queryWrapper.ne("id_",electricCheck.getId()));
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer>0){
      throw new BusinessException("该配电箱已巡检");
    }
  }

  /**
   * 设置基本属性
   * @param electricCheck
   */
  private void setBase(ElectricCheck electricCheck) {
    electricCheck.setModifyTime(new Date());
    electricCheck.setModifyId(linkappUserContextProducer.getCurrent().getId());
    //没有id就是新增,有就是编辑
    if (null == electricCheck.getId()){
      electricCheck.setCreatorId(linkappUserContextProducer.getCurrent().getId());
      electricCheck.setCreateTime(new Date());
      electricCheck.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }
    //处理检查项
    String content = electricCheck.getContent();
    if(StringUtils.isNotEmpty(content)){
      List<ElectricOptionDTO> optionList = JSONUtil.toList(content, ElectricOptionDTO.class);
      List<ElectricOptionDTO> optionDTOS = optionList.stream()
          .filter(o -> Integer.valueOf(0).equals(o.getValue())).collect(Collectors.toList());
      electricCheck.setStatus(optionDTOS.size() < 1?0:1);
    }
  }

  @Override
  public IPage<ElectricCheckPhotoAlbumDTO> selectPhotoAlbumByPage(
      RequestModel<ElectricCheckPhotoAlbumQueryDTO> requestModel) {
    Page page = requestModel.getPage();
    ElectricCheckPhotoAlbumQueryDTO queryDTO = requestModel.getCustomQueryParams();
    //项目id 过滤
    queryDTO.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    IPage<ElectricCheckPhotoAlbumDTO> pagelist = baseMapper.selectPhotoAlbumByPage(page, queryDTO);
    pagelist.getRecords().forEach(p->setPhotos(p));
    return pagelist;
  }

  private void setPhotos(ElectricCheckPhotoAlbumDTO dto){
    List<String> photos = new ArrayList<>();
    String photo = dto.getPhoto();
    if(StringUtils.isNotEmpty(photo)){
      photos.addAll(Arrays.asList(photo.split(",")));
    }
    dto.setPhotos(photos);
  }

  @Autowired
  @Qualifier("ossInternal")
  private ObjectStorageInternalService ossClient;

  @Value("${oss.dir}")
  private String dir;

  @Value("${oss.bucket}")
  private String bucket;

  @Value("${oss.readHost}")
  private String readHost;

  private final String prefix = "配电箱";

  @Override
  public int photoAlbumCount(ElectricCheckPhotoAlbumQueryDTO queryDto) {
    //项目id 过滤
    queryDto.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    List<ElectricCheckPhotoAlbumDTO> list = baseMapper
        .selectPhotoAlbumByPage(queryDto);
    int total = 0;
    if(CollectionUtil.isNotEmpty(list)){
      for (ElectricCheckPhotoAlbumDTO dto : list) {
        setPhotos(dto);
        if(CollectionUtil.isNotEmpty(dto.getPhotos())){
          total += dto.getPhotos().size();
        }
      }
    }
    return total;
  }

  @Override
  public String exportPhotoAlbum(ElectricCheckPhotoAlbumQueryDTO dto) {
    //项目id 过滤
    dto.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    String fileName = null;
    List<ElectricCheckPhotoAlbumDTO> list = baseMapper
        .selectPhotoAlbumByPage(dto);
    List<FileExt> fileExtList = new ArrayList<>();
    if(CollectionUtil.isNotEmpty(list)){

      long total = 0;
      if(CollectionUtil.isNotEmpty(list)){
        for (ElectricCheckPhotoAlbumDTO p : list) {
          setPhotos(p);
          if(CollectionUtil.isNotEmpty(p.getPhotos())){
            total += p.getPhotos().size();
          }
        }
      }
      if(total > 100){
        throw new RuntimeException("相册导出失败！相册导出不能超过100张");
      }

      for (ElectricCheckPhotoAlbumDTO p : list) {
        List<String> photos = p.getPhotos();
        if (CollectionUtil.isNotEmpty(photos)) {
          List<String> fileUrlList = new ArrayList<>();
          for (int i = 0; i < photos.size(); i++) {
            String singleFile = photos.get(i);
            fileUrlList.add(singleFile);
          }
          long count = 0;
          for (String url : fileUrlList) {

            if (StringUtils.isNotEmpty(url)) {
              url = url.replace("+", "%2B");
              url = url.replace("&", "%26");
            } else {
              log.error("打包失败：名称为空");
              continue;
            }
            FileExt fileInfoByUrl = ExportUtil.getFileInfoByUrl(url,prefix,
                com.easylinkin.linkappapi.common.utils.DateUtil.getyyyyMMddHHmmssSSSNumberString(p.getCreateTime()),p.getStatus() == 0 ?"正常":"异常",count);
            if (null != fileInfoByUrl && null != fileInfoByUrl.getInputStream()) {
              fileExtList.add(fileInfoByUrl);
              count ++;
            } else {
              log.error("打包失败：名称【{}】", url);
            }
          }
        }
      }
      
    }


    //开始导出
    InputStream fileInputStream = null;
    try {
      String today = com.easylinkin.linkappapi.common.utils.DateUtil.getyyyyMMddHHmmssSSSNumberString(new Date());
      fileInputStream = ZipFileUtil.getFileInputStream(today, fileExtList);
      //上传文件到oss
      String resultFilename =
           prefix + "_"+ today + ".zip";
      ossClient.putObject(bucket, resultFilename, fileInputStream, "application/octet-stream");
      fileName = ossService.generateUrl(resultFilename);
    } catch (Exception e) {
      log.error("打包失败：", e);
    } finally {
      // 关闭流
      try {
        if (null != fileInputStream) {
          fileInputStream.close();
        }
      } catch (IOException e) {
        log.error("打包失败：", e);
      }
    }
    return fileName;
  }

  /**
   * 查询巡检月视图
   */
  @Override
  public List<ElectricCheckDTO> monthList(ElectricCheckDTO electricCheckDTO) {
    //计算总天数
    String[] split = electricCheckDTO.getMouthStr().split("-");
    int lengthOfMonth = DateUtil
        .lengthOfMonth(Integer.valueOf(split[1]), DateUtil.isLeapYear(Integer.valueOf(split[0])));
    //查询当月的巡检记录
    List<ElectricCheckDTO> electricCheckDTOS = baseMapper.monthList(electricCheckDTO);
    //查询配置项
    List<ElectricOption> options = electricOptionService.options();
    //伪造一个电工签名
    ElectricOption electricOption = new ElectricOption();
    electricOption.setContent("电工签名");
    options.add(electricOption);
    List<ElectricCheckDTO> resultList = new ArrayList<>();
    options.forEach(o ->{
      ElectricCheckDTO checkDTO = new ElectricCheckDTO();
      checkDTO.setContent(o.getContent());
      List<String> monthList = new ArrayList<>();
      for (int i = 1; i <= lengthOfMonth; i++) {
        String s = "";
        SimpleDateFormat d = new SimpleDateFormat("d");
        int finalI = i;
        List<ElectricCheckDTO> dtos = electricCheckDTOS.stream()
            .filter(e -> Integer.valueOf(d.format(e.getCheckTime())).equals(finalI))
            .collect(Collectors.toList());
        if (dtos.size() > 0){
          ElectricCheckDTO dto = dtos.get(0);
          List<ElectricOptionDTO> optionList = JSONUtil.toList(dto.getContent(), ElectricOptionDTO.class);
          if (o.getContent().equals("电工签名")){
            s = dto.getCheckUserName();
          }else {
            long count = optionList.stream().filter(op -> op.getContent().equals(o.getContent()))
                .count();
            s = count > 0?"√":"-";
          }
        }
        monthList.add(s);
      }
      checkDTO.setMouthList(monthList);
      resultList.add(checkDTO);
    });
    return resultList;
  }

  /**
   * 导出巡检月视图
   */
  @Override
  public XWPFDocument monthExport(ElectricCheckDTO electricCheckDTO) throws Exception {
    List<Map<String, Object>> sList = new ArrayList<>();
    //查询配电箱编号
    List<String> ids = electricCheckDTO.getIds();
    List<ElectricBox> boxes = new ArrayList<>();
    if (ids.size()>0){
      boxes = electricBoxMapper.selectBatchIds(ids);
    }
    String[] split = electricCheckDTO.getMouthStr().split("-");
    int lengthOfMonth = DateUtil
        .lengthOfMonth(Integer.valueOf(split[1]), DateUtil.isLeapYear(Integer.valueOf(split[0])));
    //项目信息
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    LinkappTenant query = new LinkappTenant();
    query.setId(tenantId);
    LinkappTenant linkappTenant = linkappTenantMapper.selectLinkappTenant(query);
    List<ElectricBox> finalBoxes = boxes;
    if (ids.size() < 1){
      Map<String, Object> map = new HashMap<>();
      map.put("year",split[0]);
      map.put("mouth",Integer.valueOf(split[1]));
      //项目信息
      map.put("projectName",linkappTenant.getPlatformProjectName());
//      map.put("code",codes.get(0));
      List<ElectricCheckDTO> checkDTOS = new ArrayList<>();
      //组织列表数据
      getData(map, checkDTOS);
      sList.add(map);
    }else {
      ids.forEach(id ->{
        Map<String, Object> map = new HashMap<>();
        map.put("year",split[0]);
        map.put("mouth",Integer.valueOf(split[1]));
        //项目信息
        map.put("projectName",linkappTenant.getPlatformProjectName());
        //配电箱编码
        List<String> codes = finalBoxes.stream().filter(b -> b.getId().equals(id)).map(b -> b.getCode())
            .collect(Collectors.toList());
        if (codes.size() > 0){
          map.put("code",codes.get(0));
        }
        electricCheckDTO.setElectricBoxId(id);
        List<ElectricCheckDTO> checkDTOS = this.monthList(electricCheckDTO);
        //组织列表数据
        getData(map, checkDTOS);
        sList.add(map);
      });
    }
    //用easyPoi导出
    XWPFDocument doc = WordExportUtil.exportWord07(new ClassPathResource("templates/electric"+lengthOfMonth+".docx").getPath(), sList);
    return doc;
  }

  /**
   * 组织月视图数据
   * @param map
   * @param checkDTOS
   */
  private void getData(Map<String, Object> map, List<ElectricCheckDTO> checkDTOS) {
    List<Map<String, Object>> sonList = new ArrayList<>();
    checkDTOS.forEach(c -> {
      Map<String, Object> sonMap = new HashMap<>();
      sonMap.put("content", c.getContent());
      for (int i = 1; i <= c.getMouthList().size(); i++) {
        if (c.getContent().equals("电工签名")) {
          sonMap.put(i + "", "");
        } else {
          sonMap.put(i + "", c.getMouthList().get(i - 1));
        }
      }
      sonList.add(sonMap);
    });
    map.put("list", sonList);
  }

  @Override
  public void refreshAllStatus() {
    QueryWrapper<ElectricCheck> queryWrapper = new QueryWrapper<>();
    List<ElectricCheck> electricChecks = electricCheckMapper.selectList(queryWrapper);
    if(CollectionUtil.isNotEmpty(electricChecks)){
      electricChecks.stream().forEach(p->{
        //处理检查项
        String content = p.getContent();
        if(StringUtils.isNotEmpty(content)){
          updateOne(p);
        }
      });
    }

  }
}
